package com.guigu.servicegoods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.config.CacheKey;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.Categorys;
import com.guigu.servicegoods.domain.TbOrderItem;
import com.guigu.servicegoods.domain.TbSku;
import com.guigu.servicegoods.mapper.TbSkuMapper;
import com.guigu.servicegoods.service.TbSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbSkuServiceImpl extends ServiceImpl<TbSkuMapper, TbSku> implements TbSkuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbSkuMapper skuMapper;

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbSku> wrapper = createExample(searchMap);
        Page<TbSku> pageSku = new Page<>(page,size);
        baseMapper.selectPage(pageSku,wrapper);
        return Result.ok().data("row",pageSku.getRecords()).data("total",pageSku.getTotal());
    }

    @Override
    public void saveAllPriceToRedis() {
        //检查缓存是否存在价格数据
        if(!redisTemplate.hasKey(CacheKey.SKU_PRICE)){
            System.out.println("加载全部价格");
            List<TbSku> skuList = baseMapper.selectList(null);
            for(TbSku sku:skuList){
                if("1".equals(sku.getStatus())){
                    redisTemplate.boundHashOps(CacheKey.SKU_PRICE).put(sku.getId(),sku.getPrice());
                }
            }
        }else{
            System.out.println("已存在价格数据，没有全部加载");
        }
    }

    @Override
    public Integer findByIdPrice(String skuId) {
        return (Integer)redisTemplate.boundHashOps(CacheKey.SKU_PRICE).get(skuId);
    }

    @Override
    public void savePriceToRedisById(String skuId, Integer price) {
        redisTemplate.boundHashOps(CacheKey.SKU_PRICE).put(skuId,price);
    }

    @Override
    public void deletePriceFromRedis(String id) {
        redisTemplate.boundHashOps(CacheKey.SKU_PRICE).delete(id);
    }

    @Override
    public boolean deductionStock(List<TbOrderItem> orderItemList) {
        // 检查是否可以扣减库存
        boolean idDeduction=true;//是否可以扣减
        for (TbOrderItem orderItem : orderItemList){
            TbSku sku = baseMapper.selectById(orderItem.getSkuId());
            if (sku == null) {
                idDeduction = false;
                break;
            }
            if(!"1".equals(sku.getStatus())){
                idDeduction = false;
                break;
            }
            if (sku.getNum().intValue()<orderItem.getNum().intValue()){
                idDeduction = false;
                break;
            }
        }
        // 执行扣减
        if(idDeduction) {
            for (TbOrderItem orderItem: orderItemList) {
                skuMapper.deductionStock(orderItem.getSkuId(),orderItem.getNum()); // 扣减库存
                skuMapper.addSaleNum(orderItem.getSkuId(),orderItem.getNum());
            }
        }
        return idDeduction;
    }

    // 根据查询条件封装模块对象
    private QueryWrapper<TbSku> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbSku> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            if(searchMap.get("id")!=null)
                wrapper.eq("id",searchMap.get("id"));
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name")))
                wrapper.like("name",searchMap.get("name"));
        }
        return wrapper;
    }


    /**
     * 只条件查询  谢尚峰插入
     * @param searchMap
     * @return
     */
    @Override
    public List<TbSku> findList(Map<String, Object> searchMap) {
//        Example example = new Example(Sku.class);
//        Example.Criteria criteria = example.createCriteria();
//        if(!StringUtils.isEmpty(searchMap.get("id")))
//            criteria.andEqualTo("id",searchMap.get("id"));
//        if(!StringUtils.isEmpty(searchMap.get("name")))
//            criteria.andLike("name","%" + searchMap.get("name") + "%");
//        // 修改给order数据进行使用查
//        if (!StringUtils.isEmpty(searchMap.get("skuId"))) {
//            String string = (String) searchMap.get("skuId");
//            String[] split = string.split(",");
//            criteria.andIn("id", Arrays.asList(split));
//        }

        QueryWrapper<TbSku> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(searchMap.get("id"))) {
            wrapper.eq("id", searchMap.get("id"));
        }
        if(!StringUtils.isEmpty(searchMap.get("name"))) {
            wrapper.eq("name", "%" + searchMap.get("name"));
        }
        //修改给order数据进行使用查
        if(!StringUtils.isEmpty(searchMap.get("skuId"))) {
            String string = (String) searchMap.get("skuId");
            List list = new ArrayList();
            for(int i=0; i<string.split(",").length;i++){
                list.add(string.split(",")[i]);
            }
            wrapper.in("id",list);
        }
        List<TbSku> albumList = this.skuMapper.selectList(wrapper);
        return albumList;
    }

    // 查询所有数据
    @Override
    public List<TbSku> findAll() {
        return this.skuMapper.selectList(null);
    }
}
